package inline;

import android.content.Context;
import android.os.Build;
import android.util.Log;
import android.util.Pair;

import com.bytedance.common.utility.reflect.Reflect;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

public class PluginLoader {
    public static Field findField(Object target, String fieldName) throws NoSuchFieldException {
        Class clazz = target.getClass();
        while (true) {
            if (clazz == null) {
                throw new NoSuchFieldException("Field " + fieldName + " not found in " + target.getClass());
            }
            try {
                Field field = clazz.getDeclaredField(fieldName);
                if (!field.isAccessible()) {
                    field.setAccessible(true);
                }
                return field;
            } catch (NoSuchFieldException e) {
                clazz = clazz.getSuperclass();
            }
        }
    }

    public static void expandFieldArray(Object instance, String fieldName, Object[] extraElements) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
        Field field = PluginLoader.findField(instance, fieldName);
        Object[] original = (Object[]) field.get(instance);
        Object combined = Array.newInstance(original.getClass().getComponentType(), original.length + extraElements.length);
        System.arraycopy(original, 0, combined, 0, original.length);
        System.arraycopy(extraElements, 0, combined, original.length, extraElements.length);
        field.set(instance, combined);
    }

    public static void b(ClassLoader classLoader, List arg5) {
        try {
            String[] v1 = new String[arg5.size()];
            Iterator iterator = arg5.iterator();
            while (iterator.hasNext()) {
                v1[0] = ((File) iterator.next()).getAbsolutePath() + "/";
            }
            PluginLoader.expandFieldArray(classLoader, "mLibPaths", v1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void installV9(ClassLoader classLoader, List<File> arg6) {
        try {
            Reflect reflect = Reflect.on(classLoader);
            List<String> libraryPathElements = (List<String>) reflect.getFieldValue("libraryPathElements", new Class[0]);
            Iterator<File> iterator = arg6.iterator();
            while (iterator.hasNext()) {
                String addPath = iterator.next().getAbsolutePath() + "/";
                if (libraryPathElements != null) {
                    libraryPathElements.add(addPath);
                }
            }
            reflect.set("libraryPathElements", libraryPathElements);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void installLibs(Context context, List arg9) {
        Object v1_1;
        Iterator v3;
        Object v0_2;
        Reflect reflect;
        ClassLoader classLoader = context.getClassLoader();
        for (String className = classLoader.getClass().getName(); true; className = classLoader.getClass().getName()) {
            if (!className.startsWith("com.ss.android") && !className.startsWith("com.bytedance")) {
                if (Build.VERSION.SDK_INT >= 23) {
                    try {
                        final Object dexPathList = PluginLoader.findField(classLoader, "pathList").get(classLoader);
                        reflect = Reflect.on(dexPathList);
                        List<File> origLibDirs = (List<File>) reflect.getFieldValue("nativeLibraryDirectories", new Class[0]);
                        v3 = arg9.iterator();
                        v1_1 = origLibDirs;
                        break;
                    } catch (Exception e) {
                        e.printStackTrace();
                        return;
                    }
                } else {
                    if (Build.VERSION.SDK_INT >= 14) {
                        try {
                            PluginLoader.expandFieldArray(PluginLoader.findField(classLoader, "pathList").get(classLoader), "nativeLibraryDirectories", arg9.toArray(new File[arg9.size()]));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else if (Build.VERSION.SDK_INT >= 9) {
                        PluginLoader.installV9(classLoader, arg9);
                    } else {
                        PluginLoader.b(classLoader, arg9);
                    }
                    return;
                }
            }
            classLoader = classLoader.getParent();
        }

        try {
            while (v3.hasNext()) {
                v0_2 = v3.next();
                if (v1_1 != null) {
                    ((List) v1_1).add(v0_2);
                    continue;
                }

                v1_1 = new ArrayList();
                ((List) v1_1).add(v0_2);
            }

            reflect.set("nativeLibraryDirectories", v1_1);
            ArrayList v3_1 = new ArrayList((Collection) v1_1);
            v3_1.addAll((Collection) reflect.getFieldValue("systemNativeLibraryDirectories", new Class[0]));
            if (Build.VERSION.SDK_INT >= 26) {
                reflect.set("nativeLibraryPathElements", reflect.call("makePathElements", new Class[]{List.class}, new Object[]{v3_1}));
                return;
            }

            ArrayList v4 = new ArrayList();
            reflect.set("nativeLibraryPathElements", reflect.call("makePathElements", new Class[]{List.class, File.class, List.class}, new Object[]{v3_1, null, v4}));
            v0_2 = reflect.get("dexElementsSuppressedExceptions", new Class[0]).target;
            if (v4.size() <= 0) {
                return;
            }
            if (v0_2 == null) {
                v0_2 = v4.toArray(new IOException[v4.size()]);
            } else {
                IOException[] ioes = new IOException[v4.size() + ((IOException[]) v0_2).length];
                v4.toArray(ioes);
                System.arraycopy(v0_2, 0, ioes, v4.size(), ((IOException[]) v0_2).length);
                v0_2 = ioes;
            }
            reflect.set("dexElementsSuppressedExceptions", v0_2);
        } catch (Exception v0_1) {
            v0_1.printStackTrace();
        }
        return;
    }

    public static Method findMethod(Object arg3, String arg4, Class... arg5) throws NoSuchMethodException {
        Method v1_1;
        Class v0 = arg3.getClass();
        while (true) {
            if (v0 == null) {
                throw new NoSuchMethodException("Method " + arg4
                        + " with parameters " + Arrays.asList(((Object[]) arg5)) + " not found in " + arg3.getClass());
            }

            try {
                v1_1 = v0.getDeclaredMethod(arg4, arg5);
                if (!v1_1.isAccessible()) {
                    v1_1.setAccessible(true);
                }

                return v1_1;
            } catch (NoSuchMethodException v1) {
                v0 = v0.getSuperclass();
                continue;
            }
        }
    }

    public static void installV19(ClassLoader classLoader, List<File> additionalClassPathEntries, File optimizedDirectory) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, InvocationTargetException, NoSuchMethodException {
        IOException[] v0_3;
        Method makePathElements;
        Field v11 = null;
        final Field pathListField = PluginLoader.findField(classLoader, "pathList");
        Object dexPathList = pathListField.get(classLoader);
        ArrayList suppressedExceptions = new ArrayList();
        ArrayList v4 = new ArrayList(additionalClassPathEntries);
        if (Build.VERSION.SDK_INT >= 23) {
            makePathElements = PluginLoader.findMethod(dexPathList, "makePathElements", List.class, File.class, List.class);
        } else {
            makePathElements = PluginLoader.findMethod(dexPathList, "makeDexElements", ArrayList.class, File.class, ArrayList.class);
        }
        PluginLoader.expandFieldArray(dexPathList, "dexElements", (Object[]) makePathElements.invoke(dexPathList, v4, optimizedDirectory, suppressedExceptions));
        if (suppressedExceptions.size() > 0) {
            Iterator<IOException> iterator = suppressedExceptions.iterator();
            while (iterator.hasNext()) {
                Log.w("PluginLoader", "Exception in makeDexElement", iterator.next());
            }
            PluginLoader.findField(dexPathList, "dexElementsSuppressedExceptions");
            IOException[] v0_1 = (IOException[]) v11.get(classLoader);
            if (v0_1 == null) {
                v0_3 = (IOException[]) suppressedExceptions.toArray(new IOException[suppressedExceptions.size()]);
            } else {
                IOException[] v1_2 = new IOException[suppressedExceptions.size() + v0_1.length];
                suppressedExceptions.toArray(v1_2);
                System.arraycopy(v0_1, 0, v1_2, suppressedExceptions.size(), v0_1.length);
                v0_3 = v1_2;
            }
            v11.set(dexPathList, v0_3);
        }
    }

    public static void install(Context context, List<Pair<List<File>, File>> pluginDexAndLibList, File optimizedDirectory) {
        if (context != null) {
            try {
                ArrayList additionalClassPathEntries = new ArrayList();
                ArrayList libDirList = new ArrayList();
                Iterator<Pair<List<File>, File>> iterator = pluginDexAndLibList.iterator();
                while (iterator.hasNext()) {
                    Pair<List<File>, File> pair = iterator.next();
                    additionalClassPathEntries.addAll(pair.first);
                    libDirList.add(pair.second);
                }

                ClassLoader classLoader = context.getClassLoader();
                for (String className = classLoader.getClass().getName(); true; className = classLoader.getClass().getName()) {
                    if (!className.startsWith("com.ss.android") && !className.startsWith("com.bytedance")) {
                        if (Build.VERSION.SDK_INT >= 19) {
                            PluginLoader.installV19(classLoader, additionalClassPathEntries, optimizedDirectory);
                        } else {
                            Object dexPathList = PluginLoader.findField(classLoader, "pathList").get(classLoader);
                            PluginLoader.expandFieldArray(dexPathList, "dexElements", (Object[]) PluginLoader.findMethod(dexPathList, "makeDexElements", new Class[]{ArrayList.class, File.class}).invoke(dexPathList, new ArrayList(additionalClassPathEntries), optimizedDirectory));
                        }
                        PluginLoader.installLibs(context, libDirList);
                        return;
                    }
                    classLoader = classLoader.getParent();
                }
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
        }
    }
}
